<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>TechStore - Product Search</title>
    <script src="https://cdn.tailwindcss.com"></script>
  </head>
  <body class="bg-gray-50 min-h-screen">
    <header class="bg-white shadow-sm border-b">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
        <h1 class="text-3xl font-bold text-gray-900">
          🛍️ TechStore - Find Your Perfect Product
        </h1>
      </div>
    </header>

    <main class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <form onsubmit="event.preventDefault(); searchProducts();" class="mb-8">
        <div class="bg-white rounded-lg shadow-sm border p-6">
          <h2 class="text-lg font-semibold text-gray-900 mb-4">
            Product Search
          </h2>
          <div class="flex flex-col sm:flex-row gap-4">
            <div class="flex-1">
              <label
                for="searchQuery"
                class="block text-sm font-medium text-gray-700 mb-2"
                >Search Products:</label
              >
              <input
                type="text"
                id="searchQuery"
                placeholder="Search for phones, laptops, headphones..."
                class="w-full px-4 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                required />
            </div>
            <div class="flex items-end">
              <button
                type="submit"
                class="bg-blue-600 hover:bg-blue-700 text-white px-6 py-2 rounded-md font-medium transition-colors">
                🔍 Search
              </button>
            </div>
          </div>
        </div>
      </form>

      <div class="bg-white rounded-lg shadow-sm border p-4 mb-8">
        <div class="flex items-center justify-between">
          <div>
            <h3 class="text-sm font-medium text-gray-900">
              Live Notifications
            </h3>
            <p id="status" class="text-xs text-gray-500 mt-1">
              🟡 Connecting to live notifications...
            </p>
          </div>
          <div class="w-2 h-2 bg-yellow-400 rounded-full animate-pulse"></div>
        </div>
      </div>

      <section id="searchResults">
        <h2 class="text-2xl font-bold text-gray-900 mb-4">Search Results</h2>
        <div class="bg-white rounded-lg shadow-sm border p-6">
          <p class="text-gray-600 italic">
            🔍 Enter a search term above to find products
          </p>
        </div>
      </section>
    </main>

    <!-- HTML Dialog for notifications -->
    <dialog id="notificationDialog" class="rounded-lg shadow-xl border">
      <div class="bg-white p-6 rounded-lg">
        <h3 class="text-lg font-semibold text-gray-900 mb-4">
          🔔 Live Search Activity
        </h3>
        <p id="notificationMessage" class="text-gray-700 mb-6"></p>
        <div class="flex justify-end">
          <button
            onclick="closeNotification()"
            autofocus
            class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-md font-medium transition-colors">
            OK
          </button>
        </div>
      </div>
    </dialog>

    <script>
      let ws = null;
      let sessionId = null;

      window.onload = function () {
        sessionId = "session_" + Date.now();
        connectWebSocket();
      };

      function connectWebSocket() {
        const statusDiv = document.getElementById("status");

        ws = new WebSocket("ws://localhost:8000/ws");

        ws.onopen = function () {
          statusDiv.innerHTML =
            "🟢 Connected - You will see when others search for products";

          statusDiv.className = "text-sm text-green-600";

          console.log("Connected to WebSocket");
        };

        ws.onmessage = function (event) {
          try {
            const notification = JSON.parse(event.data);
            if (notification.type === "search") {
              showSearchNotification(notification);
            }
          } catch (error) {
            console.error("Error parsing notification:", error);
          }
        };

        ws.onclose = function () {
          statusDiv.innerHTML = "🔴 Disconnected from live notifications";

          statusDiv.className = "text-sm text-red-600";

          console.log("Disconnected from WebSocket");
        };

        ws.onerror = function (error) {
          statusDiv.innerHTML = "❌ Connection error";
          statusDiv.className = "text-sm text-red-600";

          console.error("WebSocket error:", error);
        };
      }

      function showSearchNotification(notification) {
        // Skip notifications from the same session (same browser window)
        if (notification.session_id === sessionId) {
          return;
        }

        const dialog = document.getElementById("notificationDialog");
        const messageElement = document.getElementById("notificationMessage");

        messageElement.innerHTML = `<p><strong>Hot search alert!</strong> Other users are looking for <em>"${notification.query}"</em> right now.</p>`;

        dialog.showModal();
      }

      function closeNotification() {
        const dialog = document.getElementById("notificationDialog");
        dialog.close();
      }

      async function searchProducts() {
        const query = document.getElementById("searchQuery").value.trim();
        const resultsDiv = document.getElementById("searchResults");

        if (!query) {
          resultsDiv.innerHTML = `
            <h2 class="text-2xl font-bold text-gray-900 mb-4">Search Results</h2>
            <div class="bg-white rounded-lg shadow-sm border p-6">
              <p class="text-red-600 font-medium">⚠️ Please enter a search term</p>
            </div>
          `;
          return;
        }

        resultsDiv.innerHTML = `
          <h2 class="text-2xl font-bold text-gray-900 mb-4">Search Results</h2>
          <div class="bg-white rounded-lg shadow-sm border p-6">
            <p class="text-gray-600 italic">🔍 Searching TechStore inventory...</p>
          </div>
        `;

        try {
          const response = await fetch(
            `/search?q=${encodeURIComponent(
              query
            )}&session_id=${encodeURIComponent(sessionId)}`
          );
          const data = await response.json();

          if (response.ok) {
            displaySearchResults(data);
          } else {
            throw new Error(data.error || "Search failed");
          }
        } catch (error) {
          resultsDiv.innerHTML = `
            <h2 class="text-2xl font-bold text-gray-900 mb-4">Search Results</h2>
            <div class="bg-white rounded-lg shadow-sm border p-6">
              <h3 class="text-lg font-semibold text-red-600 mb-2">❌ Search Error</h3>
              <p class="text-gray-700"><strong>Error:</strong> ${error.message}</p>
            </div>
          `;
        }
      }

      function displaySearchResults(data) {
        const resultsDiv = document.getElementById("searchResults");

        if (data.results.length === 0) {
          resultsDiv.innerHTML = `
            <h2 class="text-2xl font-bold text-gray-900 mb-4">Search Results</h2>
            <div class="bg-white rounded-lg shadow-sm border p-6">
              <h3 class="text-lg font-semibold text-red-600 mb-2">❌ No products found</h3>
              <p class="text-gray-700 mb-2">No products match "<strong>${data.query}</strong>"</p>
              <p class="text-gray-600 italic">Try searching for: iPhone, laptop, headphones, watch, etc.</p>
            </div>
          `;
          return;
        }

        let html = `<h2 class="text-2xl font-bold text-gray-900 mb-4">✅ Found ${data.total} products for "${data.query}"</h2>`;

        data.results.forEach((product) => {
          html += `
            <div class="bg-white rounded-lg shadow-sm border p-6 mb-4">
              <h3 class="text-xl font-semibold text-gray-900 mb-3">${
                product.product_name
              }</h3>
              <p class="text-2xl font-bold text-green-600 mb-3">💰 $${product.price.toFixed(
                2
              )}</p>
              <p class="text-gray-600">${product.description}</p>
            </div>
          `;
        });

        resultsDiv.innerHTML = html;
      }
    </script>
  </body>
</html>
